#include "punchingmachine.h"
#include "ui_punchingmachine.h"
#include "common.h"
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonDocument>
#include "../../scale/scaleamendcalibration.h"
#include "lock_dlg.h"
#include "../../DeviceState/devicestate.h"
#include "../../DataBase/dbtab_punchingmachine.h"
#include "../../scrollwarn/scrolltextwidget.h"
#include "../../input/inputdialog.h"
#include <iostream>
#include <exception>
#include <QMessageBox>
#include "perssiondlg.h"
#include "connectdlg.h"
using namespace std;

#define TIMES   30
#define UserRole  "userrole"

bool PunchingMachine::QC_Scan_ckeck = false;
bool PunchingMachine::l_QC_Scan_ckeck = false;
bool PunchingMachine::_orderBegin = false;
bool PunchingMachine::Equipment_ckeck = false;
bool PunchingMachine::l_Equipment_ckeck = false;

int PunchingMachine::m_systemStatus;
PunchingMachine::PunchingMachine(MainWindow *parent) :
    MainWidget(parent),
    ui(new Ui::PunchingMachine),
    m_modbusWnd(NULL),
    mStandardPara(new StandardPara{"","","","","","","","","","","","","","","","","","","","","","","","",""}),
    m_standardpara_temp({"","","","","","","","","","","","","","","","","","","","","","","","",""}),
    m_register_flag(false),
    tProctionInfo({"","","","","","","","","","","",""}),
    AlarmList({"轴温超温1","轴温超温2","轴温超温3","","","","","","","","","","卷料厚度不足","网络异常","等待刷卡","订单完成"}),
    m_accelarateScale(NULL),
    timeId(startTimer(100)),
    m_heartBeatTimer(new QTimer(0)),
    /*----Chenjiangang20181122*/
    readScaleComDelay_count(0),
    /*----zhanglong*/
    m_freshLEDTimer(new QTimer(0)),
    Check_DistenceTimer(new QTimer(0)),
    tmp(0),
    /*----zhanglong*/
    Alarm_Count(0),
    TeAlarm_Count(0),
    TeAlarm_Count1(0),
    TeAlarm_Count2(0),
    DistenceShort(0),
    DistenceLong_max(0),
    DistenceLong_min(0),
    DistenceCount(0),
    DistenceWorkCount1(0),
    DistenceWorkCount2(0),
    distence(0),
    //m_systemStatus(0),
    m_ammeterDate(NULL),
    m_postDeviceDetail_flag(false),
    m_pos_currentCount(false),
    l_systemStatus(0),
    //m_temperatureThread(NULL),
    m_currentCount_temp(""),
    m_updateCurrentCountTimer(new QTimer(0)),
    m_scaleAmendInstance(ScaleAmendCalibration::getobj()),
    m_timerAutoSend(new QTimer(this)),
    m_current_taskId(""),
    onlinetimeId(startTimer(5000*10)),//50 seconds
    m_task_timeId(startTimer(500)),
    m_orderFinish_flag(false),
    _iNum(0),
    _badNum(0),
    _objToserver(QJsonObject()),
    _timer30sec_sendDatas(new QTimer(this))
{
    m_timerAutoSend->setSingleShot(true);
    ui->setupUi(this);
    setOrderButtonHidden();
    initFont();
    initUi();
    initHttpClient();
    initHttpServer();
    //initAccelarateScale();
    /*----zhanglong*/
    initLEDcycleTime();
    initScaleSerialSetting();
    initAmmeterScaleModbusSlave();
    /*initTemperatureThread();*/
    initLaser_distance_measuring();
    initLaser_distance_measuringSec();
    // test git
    //initModBusSetting();
    initButtonSlot();
    initQCScanCheck();
    initOrderRecordShow();
    initSpotDelayTime();
    connect(this,SIGNAL(toggleAutoSend(bool)),this, SLOT(onChkAutoSendToggled(bool)));
    connect(m_timerAutoSend,SIGNAL(timeout()),this, SLOT(onTimerAutoSendTimeout()));
    emit toggleAutoSend(true);

    _timerSendToserver = new QTimer(this);
    _timerSendToserver->setSingleShot(true);
    connect( _timerSendToserver, &QTimer::timeout, [=](){
        sendOperatorAndMaterial();
    });
    ui->btn_orderShow->setVisible(false);
    ui->btn_orderCompleted->setDisabled(true);
    ui->btn_manual->setProperty(UserRole, false);
    ui->btn_test->setVisible(false);
    //20181219 Chenjiangang modify UI for HJWelder-Energy-Weight

    ui->label_3->setVisible(false);
    ui->le_laserInnerDia->setVisible(false);
    ui->label_10->setVisible(false);

    ui->label_4->setVisible(false);
    ui->le_laserOuterDia->setVisible(false);
    ui->label_11->setVisible(false);

    ui->label_9->setVisible(false);
    ui->lineEdit_4->setVisible(false);
    ui->label_12->setVisible(false);

    ui->le_productNameTab->setVisible(false);
    ui->le_productName->setVisible(false);
    ui->le_workNumTab->setVisible(false);
    ui->le_workNum->setVisible(false);
    ui->le_workTimeTab->setVisible(false);
    ui->le_workTime->setVisible(false);
    ui->le_workTimeTab_2->setVisible(false);
    ui->lbl_orderNum->setVisible(false);

    ui->label_6->setVisible(false);
    ui->le_temperature->setVisible(false);
    ui->label_15->setVisible(false);
    ui->label_37->setVisible(false);
    ui->le_temperature_3->setVisible(false);
    ui->label_38->setVisible(false);
    ui->label_35->setVisible(false);
    ui->le_temperature_2->setVisible(false);
    ui->label_36->setVisible(false);
    ui->btn_login->setVisible(false);

    ui->btn_FirstCheck->setVisible(false);
    ui->btn_QCCheck->setVisible(false);
    ui->btn_orderCompleted->setVisible(false);
    ui->btn_manual->setVisible(false);
    ui->label_33->setVisible(false);
    ui->le_bad->setVisible(false);
    ui->label_34->setVisible(false);
    ui->label->setVisible(false);
    ui->le_PScaleCount->setVisible(false);
    ui->label_18->setVisible(false);

    ui->label_8->setVisible(true);
    ui->le_calibratedCount->setVisible(true);
    ui->label_16->setVisible(true);

    _timer30sec_sendDatas->start(1000 * 30);
    connect( _timer30sec_sendDatas, SIGNAL(timeout()), this, SLOT(slot_timer30sec() ));


}


void PunchingMachine::initButtonSlot()
{
    //firstCheck
    connect(ui->btn_FirstCheck,    SIGNAL(clicked(bool)),                  this,                       SLOT(firstProductionOK_toScanOperator()));
    connect(ui->btn_FirstCheck,    SIGNAL(clicked(bool)),                  this,                       SLOT(firstProductionOK_toScanOperator2()));
    //qc
    connect(ui->btn_QCCheck,       SIGNAL(clicked(bool)),                  this,                       SLOT(firstQcCheck2()));
    connect(ui->btn_QCCheck,       SIGNAL(clicked(bool)),                  this,                       SLOT(firstQcCheck()));
    connect(ui->btn_orderShow,     SIGNAL(clicked(bool)),                  this,                       SLOT(showOrder()));
    connect(ui->qc_scan_check,     SIGNAL(clicked(bool)),                  this,                       SLOT(QCCheckManualExecute()));
    connect(ui->btn_orderCompleted,SIGNAL(clicked(bool)),                  this,                       SLOT(orderCompleted_slots()));
}

void PunchingMachine::sendOperatorAndMaterial()
{
    send7Datas_first();
    m_httpClient->posOperator( m_deviceInfo->deviceType,
                               m_deviceInfo->deviceId,
                               mParent->_productionVariant.TaskId,  _objToserver.value("Operator").toObject() , DeviceState::OPERATOR_WORK_STATION );

    for( int i =0; i < _jsArrToserver.size(); ++i)
    {
        m_httpClient->posMaterial( m_deviceInfo->deviceType,
                                   m_deviceInfo->deviceId,
                                   mParent->_productionVariant.TaskId,  _jsArrToserver.at(i).toObject() );
    }
    _objToserver = QJsonObject();
    while( _jsArrToserver.size() > 0)
    {
        _jsArrToserver.removeFirst();
    }

}

void PunchingMachine::slot_timer30sec()
{
    sendUpdateTodayTask(); //订单完成抛5、7号数据
    MyMessageDialog::message(0,"友情提示"," 每30秒上抛一次ACB点焊能耗称重管控数据！",2000);
  //  qDebug() << "~~~~~  DeviceId   " << obj["DeviceId"];
  // qDebug() << "~~~~~  DeviceType   " << obj["DeviceType"];
  //  qDebug() << "~~~~~  Energy   " << Total_PowerString;
    qDebug() << "~~~~~  UpdateTime   " << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    qDebug() << "~~~~~  FinishedProduct   " <<  ui->le_calibratedCount->text();
    qDebug() << "~~~~~  Weight   " <<ui->le_PScaleWeight->text();

    /*
    "DeviceId":"HJEnergy",
    "DeviceType":"点焊机",
    "Energy":"23.5",
    "UpdateTime":"2018-12-20 18:40:23",
    "FinishedProduct": "550",
    "Weight":"600"
   */


}

void PunchingMachine::initQCScanCheck()
{
    m_qc_checkDelayTimer->start(60000*120); //120 minute
    connect(m_qc_checkDelayTimer,SIGNAL(timeout()),this,SLOT(QCCheckTimerTips()));
}
void PunchingMachine::receiveStation_fromHttp(QString station)
{
    m_currentStation = station;
}

void PunchingMachine::QCCheckManualExecute()
{
    ui->qc_scan_check->setDisabled(true);
    QC_Scan_ckeck = true;
    m_systemStatus |= 0x4000;
    initQCCheckDialog();
}

void PunchingMachine::QCCheckTimerTips()
{
    if(!_orderBegin)
    {
        return;
    }
    QC_Scan_ckeck = true;
    m_systemStatus |= 0x4000;
    ui->qc_scan_check->setEnabled(true);
}

void PunchingMachine::showOrder()
{
    showProductionOrder();
}



void PunchingMachine::acceptDefectiveValue(int val)
{
    if( val >  ui->le_workNum->text().toInt() )
    {
        MyMessageDialog::message(0,"警告！"," 不良品数量大于订单数！",2000);
        return;
    }
    _badNum = val;
    ui->le_bad->setText(QString::number(_badNum));
    showDefectiveNumTips();

}

void PunchingMachine::accpetGoodValue(int val)
{

    ui->le_calibratedCount->setText(QString::number(val));
}

void PunchingMachine::initSpotDelayTime()
{
    QTimer::singleShot(3600000,this,SLOT(spotCheckTimerTips()));
}

void PunchingMachine::spotCheckTimerTips()
{
    m_systemStatus |= 0x4000;
    Equipment_ckeck = true;
    ui->btn_SpotCheck->setEnabled(true);
}

void PunchingMachine::showDefectiveNumTips()
{
    defectiveNumTipsCheckOK();
    m_deviceState->setDeviceStation(DeviceState::FIRST_CHECK_STATION);
}



PunchingMachine::~PunchingMachine()
{
    delete ui;
}

void PunchingMachine::onChkAutoSendToggled(bool checked)
{
    int interval =3000;//500 ms
    if( checked == true )
    {
        if( interval == 0 )
        {
            interval = 1;
        }
        m_timerAutoSend->setInterval( interval );
        m_timerAutoSend->start();
    }
    else
    {
        m_timerAutoSend->stop();
    }

}

void PunchingMachine::onTimerAutoSendTimeout()//定时发送
{
    onSendCmd();
}

void PunchingMachine::onSendCmd()
{
    QByteArray writedDataSec;
    writedDataSec.resize(1);
    /*high modul CMD = 0x46-----20181206
    writedDataSec[0] = 0x46;*/
    writedDataSec[0] = 0x4D;
    m_ldmCom2->write(writedDataSec);
    m_ldmCom->write(writedDataSec);
    DistenceWorkCount1 ++;
    DistenceWorkCount2 ++;
    m_timerAutoSend->start(); // start the timmer
}

void PunchingMachine::initLEDcycleTime()
{
    /*LED cnotrol time--zhanglong*/
    m_freshLEDTimer->start(800);
    Check_DistenceTimer->start(1500);
    connect(m_freshLEDTimer,   SIGNAL(timeout()),    this,   SLOT(LEDFrashCircleTimeSlot()));
    connect(Check_DistenceTimer,   SIGNAL(timeout()),    this,   SLOT(Distance_mec_restart()));
}

void PunchingMachine::initHttpClient()
{
    connect(m_httpClient,   SIGNAL(startHttpWork()),                this,   SLOT(deviceCircleSend()));
    connect(m_httpClient,   SIGNAL(startHttpWork()),                this,   SLOT(updateCurrentCount()));
    connect(m_httpClient,   SIGNAL(registerOK(bool)),               this,   SLOT(receiveHttpRegisterOK(bool)));
    connect(m_httpClient,   SIGNAL(ipStatusSignals(bool)),          this,   SLOT(httpRegister_slots(bool)));
    connect(m_httpClient,   SIGNAL(sendUserPerssion(QString)),      this,   SLOT(receiveHttpUserPermission(QString)));
    connect(m_httpClient,   SIGNAL(orderConfirmOK()),               this,   SLOT(showOrderCheckOK_Tips()));
    connect(m_httpClient,   SIGNAL(updateDeviceState_Signals()),    this,   SLOT(updateDeviceState_Slots()));
    connect(m_httpClient,   SIGNAL(sendStation_OfHttp(QString)),    this,   SLOT(receiveStation_fromHttp(QString)));

}


void PunchingMachine::receiveHttpRegisterOK(bool registerOK)
{
    if(registerOK&& !m_pos_currentCount)
    {
        m_httpClient->posDeviceInfo(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"CurrentCount",ui->le_calibratedCount->text());
    }
}

void PunchingMachine::updateCurrentCount()
{
    m_updateCurrentCountTimer->start(1000);
    connect(m_updateCurrentCountTimer,   SIGNAL(timeout()),    this,   SLOT(updateCurrentCountCirle()));
}

void PunchingMachine::updateCurrentCountCirle()
{
    if(m_currentCount_temp.compare(ui->le_calibratedCount->text()) != 0){
        m_currentCount_temp = ui->le_calibratedCount->text();
        m_httpClient->putUpdateDevice(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"CurrentCount",ui->le_calibratedCount->text());
    }
}

void PunchingMachine::deviceCircleSend()
{
    m_heartBeatTimer->start(3000);
    connect(m_heartBeatTimer,   SIGNAL(timeout()),    this,   SLOT(deviceCircleTimeSlot()));
}

void PunchingMachine::deviceCircleTimeSlot()
{
    if (!m_postDeviceDetail_flag) {
        posDetailFun("");
        m_postDeviceDetail_flag = true;
        if(m_heartBeatTimer) {
            if (m_heartBeatTimer->isActive()) {
                m_heartBeatTimer->stop();
            }
        }
    }
}

void PunchingMachine::posDetailFun(QString sequence)
{
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"合格品数",mStandardPara->calibrationCount);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"卷料剩余量",mStandardPara->distance);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"落料重量",mStandardPara->scaleWeight);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"落料数量",mStandardPara->scaleCount);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"修正单重",mStandardPara->scale_unitWeight);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"温度1",mStandardPara->temperarture1);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"温度2",mStandardPara->temperarture2);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"温度3",mStandardPara->temperarture3);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"电压1",mStandardPara->voltage1);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"电压2",mStandardPara->voltage2);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"电压3",mStandardPara->voltage3);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"电压4",mStandardPara->voltage4);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"耗电量1",mStandardPara->ammeterData1);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"耗电量2",mStandardPara->ammeterData2);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"耗电量3",mStandardPara->ammeterData3);
    m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"耗电量4",mStandardPara->ammeterData4);
}
void PunchingMachine::putDetailFun(QString sequence)
{
    if(!sequence.isEmpty()) {
        if(sequence.compare("1") == 0) {
            if(m_standardpara_temp.calibrationCount != mStandardPara->calibrationCount){
                m_standardpara_temp.calibrationCount = mStandardPara->calibrationCount;
                //m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接规范号",mStandardPara->weldStandardNum);
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"合格品数",mStandardPara->calibrationCount);
            }
        }else if(sequence.compare("2") == 0){
            if(m_standardpara_temp.distance != mStandardPara->distance){
                m_standardpara_temp.distance = mStandardPara->distance;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"卷料剩余量",mStandardPara->distance);
            }
        }else if(sequence.compare("3") == 0){
            if(m_standardpara_temp.scaleWeight != mStandardPara->scaleWeight){
                m_standardpara_temp.scaleWeight = mStandardPara->scaleWeight;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"落料重量",mStandardPara->scaleWeight);
            }
        }else if(sequence.compare("4") == 0){
            if(m_standardpara_temp.scaleCount != mStandardPara->scaleCount){
                m_standardpara_temp.scaleCount = mStandardPara->scaleCount;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"落料数量",mStandardPara->scaleCount);
            }
        }else if(sequence.compare("5") == 0){
            if(m_standardpara_temp.scale_unitWeight != mStandardPara->scale_unitWeight){
                m_standardpara_temp.scale_unitWeight = mStandardPara->scale_unitWeight;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"修正单重",mStandardPara->scale_unitWeight);
            }
        }else if(sequence.compare("6") == 0){
            if(m_standardpara_temp.temperarture1 != mStandardPara->temperarture1){
                m_standardpara_temp.temperarture1 = mStandardPara->temperarture1;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"温度1",mStandardPara->temperarture1);
            }
        }else if(sequence.compare("7") == 0){
            if(m_standardpara_temp.temperarture2 != mStandardPara->temperarture2){
                m_standardpara_temp.temperarture2 = mStandardPara->temperarture2;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"温度2",mStandardPara->temperarture2);
            }
        }else if(sequence.compare("8") == 0){
            if(m_standardpara_temp.temperarture3 != mStandardPara->temperarture3){
                m_standardpara_temp.temperarture3 = mStandardPara->temperarture3;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"温度3",mStandardPara->temperarture3);
            }
        }else if(sequence.compare("9") == 0){
            if(m_standardpara_temp.voltage1 != mStandardPara->voltage1){
                m_standardpara_temp.voltage1 = mStandardPara->voltage1;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"电压1",mStandardPara->voltage1);
            }
        }else if(sequence.compare("10") == 0){
            if(m_standardpara_temp.voltage2 != mStandardPara->voltage2){
                m_standardpara_temp.voltage2 = mStandardPara->voltage2;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"电压2",mStandardPara->voltage2);
            }
        }else if(sequence.compare("11") == 0){
            if(m_standardpara_temp.voltage3 != mStandardPara->voltage3){
                m_standardpara_temp.voltage3 = mStandardPara->voltage3;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"电压3",mStandardPara->voltage3);
            }
        }else if(sequence.compare("12") == 0){
            if(m_standardpara_temp.voltage4 != mStandardPara->voltage4){
                m_standardpara_temp.voltage4 = mStandardPara->voltage4;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"电压4",mStandardPara->voltage4);
            }
        }else if(sequence.compare("13") == 0){
            if(m_standardpara_temp.ammeterData1 != mStandardPara->ammeterData1){
                m_standardpara_temp.ammeterData1 = mStandardPara->ammeterData1;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"耗电量1",mStandardPara->ammeterData1);
            }
        }else if(sequence.compare("14") == 0){
            if(m_standardpara_temp.ammeterData2 != mStandardPara->ammeterData2){
                m_standardpara_temp.ammeterData2 = mStandardPara->ammeterData2;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"耗电量2",mStandardPara->ammeterData2);
            }
        }else if(sequence.compare("15") == 0){
            if(m_standardpara_temp.ammeterData3 != mStandardPara->ammeterData3){
                m_standardpara_temp.ammeterData3 = mStandardPara->ammeterData3;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"耗电量3",mStandardPara->ammeterData3);
            }
        }else if(sequence.compare("16") == 0){
            if(m_standardpara_temp.ammeterData4 != mStandardPara->ammeterData4){
                m_standardpara_temp.ammeterData4 = mStandardPara->ammeterData4;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"耗电量4",mStandardPara->ammeterData4);
            }
        }
    }
}

QJsonObject PunchingMachine::getUIDatas()
{
    QJsonObject obj;
    obj.insert( "长距离直径",  ui->le_laserInnerDia->text() );
    obj.insert( "短距离直径",  ui->le_laserOuterDia->text() );
    obj.insert( "剩余卷料厚度", ui->lineEdit_4->text() );
    obj.insert( "落料重量",     ui->le_PScaleWeight->text() );
    obj.insert( "落料参考计数", ui->le_PScaleCount->text() );
    obj.insert( "温度1", ui->le_temperature->text() );
    obj.insert( "温度2", ui->le_temperature_3->text() );
    obj.insert( "温度3", ui->le_temperature_2->text() );
    obj.insert( "电压1", ui->le_vol->text() );
    obj.insert( "电压2", ui->le_vol_4->text() );
    obj.insert( "电压3", ui->le_vol_2->text() );
    obj.insert( "电压4", ui->le_vol_3->text() );
    obj.insert( "耗电量1", ui->le_power->text() );
    obj.insert( "耗电量2", ui->le_power_2->text() );
    obj.insert( "耗电量3", ui->le_power_3->text() );
    obj.insert( "耗电量4", ui->le_power_4->text() );
    obj.insert( "修正单重", ui->le_uw->text() );
    obj.insert( "合格品数量", ui->le_calibratedCount->text() );
    obj.insert( "不良品数", ui->le_bad->text() );
    return obj;
}

void PunchingMachine::initFont()
{
    {
        QFont f("DejaVu Sans",19);
        ui->le_productName->setFont(f);
        ui->le_workNum->setFont(f);
        ui->le_workTime->setFont(f);
        ui->lbl_orderNum->setFont(f);
    }
}

void PunchingMachine::initUi()
{
    ui->le_productName->setAlignment(Qt::AlignLeft);
    ui->le_workNum->setAlignment(Qt::AlignLeft);
    ui->le_workTime->setAlignment(Qt::AlignLeft);
    ui->lbl_orderNum->setAlignment(Qt::AlignLeft);
    ui->le_bad->setEnabled(false);
}


void PunchingMachine::updateDeviceState_Slots()
{
    ProductionVariant productinfo;
    queryCurrentOrder(productinfo,getCurrentTaskId());
    m_deviceState->setMachineState(DeviceState::MACHINE_WORKING);//string value is : processing
    QString deviceState;
    m_deviceState->getMachineStateString(deviceState);
    m_httpClient->putUpdateDevice(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"State",deviceState);
    /*--- POST订单状态 ----*/
    m_httpClient->postOrderState(m_deviceState->getOrderState(),m_deviceInfo->deviceType,m_deviceInfo->deviceId,productinfo.TaskId);
}

void PunchingMachine::slot_sendOperator(QString strUserName, QString strUserId, DeviceState::DeviceStion  dd)
{
    QJsonObject obj;
    obj.insert("Operator", strUserName );
    obj.insert("OperatorId", strUserId );
    obj.insert("createtime", QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
    _objToserver.insert("Operator", obj);
    m_httpClient->posOperator( m_deviceInfo->deviceType,
                                   m_deviceInfo->deviceId,
                                   mParent->_productionVariant.TaskId,  obj , dd);
}


void PunchingMachine::slot_sendMaterial(QString strCount, QString strMname, QString strMcode)
{
    QJsonObject obj;
    obj.insert("count", strCount );
    obj.insert("mname", strMname );
    obj.insert("mcode", strMcode );
    _jsArrToserver.append(obj);

}

void PunchingMachine::slot_sendGongZhang(QString strToolName,  QString strToolCode)
{
    QJsonObject obj;
    obj.insert("ToolingCode", strToolCode );
    obj.insert("ToolingName", strToolName );
    m_httpClient->posGongzhuang(m_deviceInfo->deviceType,
                                m_deviceInfo->deviceId,
                                mParent->_productionVariant.TaskId,
                                obj );
}

void PunchingMachine::slot_clearOrderMsg()
{
    ui->le_productName->clear();
    ui->le_workNum->clear();
    ui->le_workTime->clear();
    ui->lbl_orderNum->clear();
    ui->le_calibratedCount->clear();
    sendNotGood();
}

void PunchingMachine::sendUpdateTodayTask()
{
    QString status;
    if( ui->le_workNum->text().toInt() == 0 )
        status = "待机";
    else if( ui->le_calibratedCount->text().toInt() > 0 && ui->le_calibratedCount->text().toInt() <  ui->le_workNum->text().toInt() )
        status = "生产中";
    else
        status = "已完成";

    QJsonObject obj;
   // obj["productname"] = ui->le_productName->text();
   // obj["productcode"] = mParent->_productionVariant.ProductCode;
   // obj["taskstatus"] = status;
   // obj["taskyield"] = "0";
    if(ui->le_calibratedCount->text().toInt() > 0)
        obj["FinishedProduct"] = ui->le_calibratedCount->text();
    else
        obj["FinishedProduct"] = QString("0");

    if(ui->le_PScaleWeight->text().toFloat() > 0)
        obj["Weight"] = ui->le_PScaleWeight->text();  //20181220 ChenJiangang new add Weight post for HJWelder
    else
        obj["Weight"] = QString("0");

//    obj["device_property"] = QJsonObject();
//    if( mStandardPara->ammeterData.contains("KWH"))
//        mStandardPara->ammeterData.remove("KWH");


    try
    {
        float Total_Power;
        Total_Power = ui->le_power->text().toFloat()+ui->le_power_2->text().toFloat()+ui->le_power_3->text().toFloat();
        qDebug()<<"================ Total_Power:"<<Total_Power;
        QString Total_PowerString=QString::number(Total_Power);
        obj["Energy"] =Total_PowerString;

    }
    catch(exception& e)
    {
        obj["Energy"] = QString("0");
    }
   // obj["productcount"] = ui->le_workNum->text();
    obj["UpdateTime"] = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    //obj["starttime"] = startTime;
    //obj["offtime"] = endTime;
    m_httpClient->posTodayTask(m_deviceInfo->deviceType,
                               m_deviceInfo->deviceId,
                               "TJHJWelder_FixedTaskId",//mParent->_productionVariant.TaskId,
                               "task",
                               obj,
                               1);
}

void PunchingMachine::send7Datas()
{
    m_httpClient->pos7Datas(m_deviceInfo->deviceType,
                            m_deviceInfo->deviceId,
                            mParent->_productionVariant.TaskId,
                            _workArr  );
}


void PunchingMachine::send7Datas_first()
{
    QJsonArray  jsArrTemp;
    jsArrTemp.append(getUIDatas());
    m_httpClient->pos7Datas(m_deviceInfo->deviceType,
                            m_deviceInfo->deviceId,
                            mParent->_productionVariant.TaskId,
                             jsArrTemp );
    while( jsArrTemp.size()> 0)
    {
         jsArrTemp.removeFirst();
    }
}


void PunchingMachine::on_le_calibratedCount_textChanged( QString str)
{
    if( str.toInt() <= 0) //如果为0则直接清空计数，上抛数据全部清空
    {
        _iNum = 0;  //计数清0
        while(_workArr.isEmpty() == false)
            _workArr.removeFirst();
        return;
    }

    _iNum++;
    if( _iNum < TIMES )
    {
        _workArr.append( getUIDatas() );
        return ;
    }

    if( _iNum >= TIMES)
    {
        _workArr.append( getUIDatas() );
        _iNum = 0;
        send7Datas(); //每30次只发7号数据
        while(_workArr.isEmpty() == false)
            _workArr.removeFirst();
        return;
    }
}

/*void PunchingMachine::initTemperatureThread()
{
    m_temperatureThread = new TemperatureThread();
    connect(m_temperatureThread,   SIGNAL(sendTemp(float)),    this,   SLOT(readTemperature(float)),Qt::QueuedConnection);
}*/

/*temper 1*----zhanglong*/
void PunchingMachine::readTemperature(int temperature)
{

    if(temperature > 100)
    {
        TeAlarm_Count ++;
        if(TeAlarm_Count > 10)
        {
            TeAlarm_Count = 11;
            m_systemStatus |= 0x0001;
        }
    }
    else
    {
        if(TeAlarm_Count != 0)
        {
            TeAlarm_Count --;
        }
        else
        {
            m_systemStatus &= 0xfffe;
        }
    }
    QString temperature_value = QString::number(temperature) + " °c";
    ui->le_temperature->setText(temperature_value);
    mStandardPara->temperarture1 = temperature_value;
    if(m_postDeviceDetail_flag)
    {
        putDetailFun("6");
    }
}

/*temper 2*----zhanglong*/
void PunchingMachine::readTemperature_1(int temperature)
{
    /*----zhanglong*/
    if(temperature > 100)
    {
        TeAlarm_Count1 ++;
        if(TeAlarm_Count1 > 10)
        {
            TeAlarm_Count1 = 11;
            m_systemStatus |= 0x0002;
        }
    }
    else
    {
        if(TeAlarm_Count1 != 0)
        {
            TeAlarm_Count1 --;
        }
        else
        {
            m_systemStatus &= 0xfffd;
        }
    }
    if(temperature == 0)
    {
        ui->le_temperature_3->setText("");
        mStandardPara->temperarture2 = "";
        if(m_postDeviceDetail_flag)
        {
            putDetailFun("7");
        }
    }
    else
    {
        QString temperature_value = QString::number(temperature) + " °c";
        ui->le_temperature_3->setText(temperature_value);
        mStandardPara->temperarture2 = temperature_value;
        if(m_postDeviceDetail_flag)
        {
            putDetailFun("7");
        }
    }

}

/*temper 3*----zhanglong*/
void PunchingMachine::readTemperature_2(int temperature)
{
    /*----zhanglong*/
    if(temperature > 100)
    {
        TeAlarm_Count2 ++;
        if(TeAlarm_Count2 > 10)
        {
            TeAlarm_Count2 = 11;
            m_systemStatus |= 0x0004;
        }
    }
    else
    {
        if(TeAlarm_Count2 != 0)
        {
            TeAlarm_Count2 --;
        }
        else
        {
            m_systemStatus &= 0xfffb;
        }
    }
    if(temperature == 0)
    {
        ui->le_temperature_2->setText("");
        mStandardPara->temperarture3 = "";
        if(m_postDeviceDetail_flag)
        {
            putDetailFun("8");
        }
    }
    else
    {
        QString temperature_value = QString::number(temperature) + " °c";
        ui->le_temperature_2->setText(temperature_value);
        mStandardPara->temperarture3 = temperature_value;
        if(m_postDeviceDetail_flag)
        {
            putDetailFun("8");
        }
    }
}

void PunchingMachine::initAmmeterScaleModbusSlave()
{
    qDebug() << Q_FUNC_INFO;
    QString portName;
    portName = "/dev/" + m_usbPortName.port0_name;
    m_ammeterDate = new AmmeterScale(portName,"9600","8","none","1");
    /*Start LED----zhanglong*/
    m_ammeterDate->writeCmd("06","0F","00","10","RTU","02","01 00",false);
    /*Ammeter 1*----zhanglong*/
    connect(m_ammeterDate,   SIGNAL(sendAmmeterPowerData(float)),    this,   SLOT(readAmmeterPowerData(float)));
    connect(m_ammeterDate,   SIGNAL(sendAmmeterVolData(float)),    this,   SLOT(readAmmeterVolData(float)));
    /*Ammeter 2*----zhanglong*/
    connect(m_ammeterDate,   SIGNAL(sendAmmeterPowerData_1(float)),    this,   SLOT(readAmmeterPowerData_1(float)));
    connect(m_ammeterDate,   SIGNAL(sendAmmeterVolData_1(float)),    this,   SLOT(readAmmeterVolData_1(float)));
    /*Ammeter 3*----zhanglong*/
    connect(m_ammeterDate,   SIGNAL(sendAmmeterPowerData_2(float)),    this,   SLOT(readAmmeterPowerData_2(float)));
    connect(m_ammeterDate,   SIGNAL(sendAmmeterVolData_2(float)),    this,   SLOT(readAmmeterVolData_2(float)));
    /*Ammeter 4*----zhanglong*/
    connect(m_ammeterDate,   SIGNAL(sendAmmeterPowerData_3(float)),    this,   SLOT(readAmmeterPowerData_3(float)));
    connect(m_ammeterDate,   SIGNAL(sendAmmeterVolData_3(float)),    this,   SLOT(readAmmeterVolData_3(float)));
    /*Tempera 1*----zhanglong*/
    connect(m_ammeterDate,   SIGNAL(sendTemperature(int)),    this,   SLOT(readTemperature(int)));
    /*Tempera 2*----zhanglong*/
    connect(m_ammeterDate,   SIGNAL(sendTemperature_1(int)),    this,   SLOT(readTemperature_1(int)));
    /*Tempera 3*----zhanglong*/
    connect(m_ammeterDate,   SIGNAL(sendTemperature_2(int)),    this,   SLOT(readTemperature_2(int)));

}
/*Ammeter 1*----zhanglong*/
void PunchingMachine::readAmmeterPowerData(float ammeter)
{
    //QString powerData = QString::number(ammeter);
    //emit showAmmeterData(mStandardPara->ammeterData);
    ui->le_power->setText(QString::number(ammeter));
    mStandardPara->ammeterData1 = QString::number(ammeter);
    if(m_postDeviceDetail_flag)
    {
        putDetailFun("13");
    }
}
void PunchingMachine::readAmmeterVolData(float vol)
{
    //QString volData = QString::number(vol);
    //emit showAmmeterVolData(mStandardPara->ammeterVolData);
    ui->le_vol->setText(QString::number(vol));
    mStandardPara->voltage1=QString::number(vol);
    if(m_postDeviceDetail_flag)
    {
        putDetailFun("9");
    }
}

/*Ammeter 2*----zhanglong*/
void PunchingMachine::readAmmeterPowerData_1(float ammeter)
{
    //QString powerData = QString::number(ammeter);
    //emit showAmmeterData(mStandardPara->ammeterData);
    ui->le_power_2->setText(QString::number(ammeter));
    mStandardPara->ammeterData2 = QString::number(ammeter);
    if(m_postDeviceDetail_flag)
    {
        putDetailFun("14");
    }
}
void PunchingMachine::readAmmeterVolData_1(float vol)
{
    //QString volData = QString::number(vol);
    //emit showAmmeterVolData(mStandardPara->ammeterVolData);
    ui->le_vol_4->setText(QString::number(vol));
    mStandardPara->voltage2=QString::number(vol);
    if(m_postDeviceDetail_flag)
    {
        putDetailFun("10");
    }
}

/*Ammeter 3*----zhanglong*/
void PunchingMachine::readAmmeterPowerData_2(float ammeter)
{
    //QString powerData = QString::number(ammeter);
    //emit showAmmeterData(mStandardPara->ammeterData);
    ui->le_power_3->setText(QString::number(ammeter));
    mStandardPara->ammeterData3 = QString::number(ammeter);
    if(m_postDeviceDetail_flag)
    {
        putDetailFun("15");
    }
}
void PunchingMachine::readAmmeterVolData_2(float vol)
{
    //QString volData = QString::number(vol);
    //emit showAmmeterVolData(mStandardPara->ammeterVolData);
    ui->le_vol_2->setText(QString::number(vol));
    mStandardPara->voltage3=QString::number(vol);
    if(m_postDeviceDetail_flag)
    {
        putDetailFun("11");
    }
}

/*Ammeter 4*----zhanglong*/
void PunchingMachine::readAmmeterPowerData_3(float ammeter)
{
    //QString powerData = QString::number(ammeter);
    //emit showAmmeterData(mStandardPara->ammeterData);
    ui->le_power_4->setText(QString::number(ammeter));
    mStandardPara->ammeterData4 = QString::number(ammeter);
    if(m_postDeviceDetail_flag)
    {
        putDetailFun("16");
    }
}
void PunchingMachine::readAmmeterVolData_3(float vol)
{
    //QString volData = QString::number(vol);
    //emit showAmmeterVolData(mStandardPara->ammeterVolData);
    ui->le_vol_3->setText(QString::number(vol));
    mStandardPara->voltage4=QString::number(vol);
    if(m_postDeviceDetail_flag)
    {
        putDetailFun("12");
    }
}

void PunchingMachine::deleteFunc(){
    if(m_modbusWnd){
        delete m_modbusWnd;
    }
}

void PunchingMachine::initModBusSetting(){
    m_modbusWnd = ModbusRtuMaster::getobj("/dev/" + m_usbPortName.port2_name, "9600", "8","none", "1");
    
}

void PunchingMachine::setDefectValue()
{
    //TODO need finish
    ui->le_bad->setText("0");
}

void PunchingMachine::removeDefectNumEvent()
{
    ui->le_bad->removeEventFilter(this);
}
void PunchingMachine::setOrderButtonDisabled()
{
    //TODO Need finish
    ui->btn_orderCompleted->setEnabled(false);
}

void PunchingMachine::setOrderButtonShow()
{
    //TODO Need finish
}

void PunchingMachine::setOrderButtonHidden()
{
    //TODO Need finish
}

void PunchingMachine::deleteSpotScrollText()
{
    //TODO need
}

void PunchingMachine::startSpotCheckTimer()
{
    //TODO Need
}

void PunchingMachine::setCurrentOrderStatusShow(ProductionVariant &productInfo)
{
    qDebug() << Q_FUNC_INFO << "productInfo.ProductName: " << productInfo.ProductName;
    qDebug() << Q_FUNC_INFO << "productInfo.WorkNum: " << productInfo.WorkNum;
    qDebug() << Q_FUNC_INFO << "productInfo.WorkTime: " << productInfo.OrderStartTime;
    ui->le_productName->setText(productInfo.ProductName);
    ui->le_workNum->setText(productInfo.WorkNum);
    ui->le_workTime->setText(productInfo.OrderStartTime);
    ui->lbl_orderNum->setText(productInfo.TaskId);
    m_current_taskId = productInfo.TaskId;
}

void PunchingMachine::sendCloseInputDialogSignal_ByHeadMan()
{

}

void PunchingMachine::sendCloseConfirmDialogSignal_ByQcMan()
{
    //TODO
}

void PunchingMachine::enableButton(bool)
{
    //TODO maybe not need
}

void PunchingMachine::timerEvent(QTimerEvent *event)
{
    int t = event->timerId();
    if(t == onlinetimeId)
    {
        m_httpClient->putUpdateDevice(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"heartbeat","on-line-again");
    }
    if(t == timeId)
    {
        ui->lab_date->setText(QDate::currentDate().toString("yyyy-MM-dd"));
        ui->lab_time->setText(QTime::currentTime().toString("hh:mm:ss"));

        //20181220 ChenJiangang HJWelder-Energy-Weight  G-DIO 控制器上线后每30sec自动上抛能耗和称重信息
        //sendUpdateTodayTask(); //订单完成抛5、7号数据

    }

 //   if(t == timeId)
 //   {
 //       slot_timer30sec();////20181220 ChenJiangang add info for Haojing Welder Engrgy,send data every 30sec
 //   }
    if (t == m_task_timeId)
    {
        if ( !m_orderFinish_flag )
        {
            //当合格品数量 >= workNum时，订单完成
            if(  ui->le_calibratedCount->text().toInt() >= ui->le_workNum->text().toInt() && ui->le_workNum->text().toInt() > 0)
            {
                endTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
                m_orderFinish_flag = true;

                m_systemStatus |= 0x8000;

                sendUpdateTodayTask(); //订单完成抛5、7号数据
                send7Datas();
                while(_workArr.isEmpty() == false)
                    _workArr.removeFirst();

                QString tips = tr("此订单数量已完成  ，请输入不良品数！");
                MyMessageDialog *dialog = new MyMessageDialog(tips,tr("提示!"),this,tr("否"),tr("确定"));
                dialog->hideCancelBtn();
                dialog->show();

                connect(dialog, &QDialog::accepted, [=](){
                    ui->le_bad->setFocus();
                    QMouseEvent event(QEvent::MouseButtonPress, QPoint(),
                                      Qt::NoButton, Qt::NoButton, Qt::NoModifier);
                    QApplication::sendEvent(ui->le_bad, &event);
                } );

                ui->le_bad->installEventFilter(this);
                ui->btn_orderCompleted->setEnabled(true);
                _orderBegin = false;
                 QC_Scan_ckeck = false;
            }
        }
    }
}


void  PunchingMachine::initLaser_distance_measuringSec(){
    QString portName = m_usbPortName.port2_name;
#ifdef Q_OS_LINUX
    m_ldmCom2 = new QextSerialPort("/dev/" + portName);
#elif defined (Q_OS_WIN)
    if(m_ldmCom2 == NULL){
        m_ldmCom2 = new QextSerialPort(portName);
    }
#endif
    connect(m_ldmCom2, SIGNAL(readyRead()),this, SLOT(readLDMComSec()));
    m_ldmCom2->setBaudRate((BaudRateType)19200);
    m_ldmCom2->setFlowControl(FLOW_OFF);
    m_ldmCom2->setTimeout(1000);
    if(!m_ldmCom2->isOpen()){
        m_ldmCom2->open(QIODevice::ReadWrite);
    }
    m_ldmCom2->setDataBits((DataBitsType)8);
    m_ldmCom2->setParity(PAR_NONE);
    m_ldmCom2->setStopBits(STOP_1);

}

void PunchingMachine::initLaser_distance_measuring(){
    QString portName = m_usbPortName.port3_name;
#ifdef Q_OS_LINUX
    m_ldmCom = new QextSerialPort("/dev/" + portName);
#elif defined (Q_OS_WIN)
    if(m_ldmCom == NULL){
        m_ldmCom = new QextSerialPort(portName);
    }
#endif
    connect(m_ldmCom, SIGNAL(readyRead()),this, SLOT(readLDMCom()));
    m_ldmCom->setBaudRate((BaudRateType)19200);
    m_ldmCom->setFlowControl(FLOW_OFF);
    m_ldmCom->setTimeout(1000);
    if(!m_ldmCom->isOpen()){
        m_ldmCom->open(QIODevice::ReadWrite);
    }
    m_ldmCom->setDataBits((DataBitsType)8);
    m_ldmCom->setParity(PAR_NONE);
    m_ldmCom->setStopBits(STOP_1);
    emit toggleAutoSend(true);
}

void PunchingMachine::initScaleSerialSetting()
{
    //TODO Need do this
    QString portName = m_usbPortName.port1_name;

#ifdef Q_OS_LINUX
    m_scaleCom = new QextSerialPort("/dev/" + portName);
#elif defined (Q_OS_WIN)
    if(m_scaleCom == NULL){
        m_scaleCom = new QextSerialPort(portName);
    }
#endif
    connect(m_scaleCom, SIGNAL(readyRead()), this, SLOT(readScaleCom()));
    //m_scaleCom->setBaudRate((BaudRateType)9600);
    m_scaleCom->setBaudRate((BaudRateType)4800); //2018.11.20 Chenjiangang reduce baud rate from 9600 to 4800
    m_scaleCom->setFlowControl(FLOW_OFF);
    m_scaleCom->setTimeout(50);
    if(!m_scaleCom->isOpen()){
        m_scaleCom->open(QIODevice::ReadWrite);
    }
    m_scaleCom->setDataBits((DataBitsType)8);
    m_scaleCom->setParity(PAR_NONE);
    m_scaleCom->setStopBits(STOP_1);

}

void PunchingMachine::saveElectrodeCountToDataBase()
{
    //TODO 20180806 Maybe not need
}

bool PunchingMachine::eventFilter(QObject *watched, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress)
    {
        if(watched == ui->le_bad)
        {
            inputDefectiveNum();//输入焊接不良品数
        }
        else if(watched == ui->le_calibratedCount)
        {
            inputGoodNum();
        }
    }
    return QWidget::eventFilter(watched,event);
}

void PunchingMachine::inputDefectiveNum()
{
    ui->le_bad->clearFocus();
    QWidget *back = new QWidget(this);
    back->setGeometry(0,0,SCREEN_WIDTH,SCREEN_HIGH);
    back->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint); //Windows上设为透明色 需有Qt::FramelessWindowHint
    back->setAttribute(Qt::WA_TranslucentBackground,true); //Windows上设为透明色
    back->setWindowModality(Qt::WindowModal);
    back->show();
    inputDialog *inputdialog = new inputDialog(back,"请输入不良品",false,5,0,0,true);
    inputdialog->setWindowModality(Qt::WindowModal);
    inputdialog->hideSome();
    inputdialog->show();
    connect(inputdialog,SIGNAL(inputValue(int)),this,SLOT(acceptDefectiveValue(int)));
    connect(inputdialog,SIGNAL(exitInputdialog()),back,SLOT(deleteLater()));
    connect(inputdialog,SIGNAL(exitInputdialog()),inputdialog,SLOT(deleteLater()));
}

void PunchingMachine::inputGoodNum()
{
    ui->le_calibratedCount->clearFocus();
    QWidget *back = new QWidget(this);
    back->setGeometry(0,0,SCREEN_WIDTH,SCREEN_HIGH);
    back->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint); //Windows上设为透明色 需有Qt::FramelessWindowHint
    back->setAttribute(Qt::WA_TranslucentBackground,true); //Windows上设为透明色
    back->setWindowModality(Qt::WindowModal);
    back->show();
    inputDialog *inputdialog = new inputDialog(back,"请输入合格品",false,5,0,0,true);
    inputdialog->setWindowModality(Qt::WindowModal);
    inputdialog->hideSome();
    inputdialog->show();
    connect(inputdialog,SIGNAL(inputValue(int)),this,SLOT(accpetGoodValue(int)));
    connect(inputdialog,SIGNAL(exitInputdialog()),back,SLOT(deleteLater()));
    connect(inputdialog,SIGNAL(exitInputdialog()),inputdialog,SLOT(deleteLater()));
}

void PunchingMachine::escFromSettings()
{

}


void PunchingMachine::readLDMComSec(){
    if(m_ldmCom2->canReadLine()){
        DistenceWorkCount2 = 0;
        QString temp = m_ldmCom2->readAll();
        QString tempmid = temp.mid(2, 5);
        float hex = tempmid.toFloat();
        hex = hex * 1000.00;
        float initSize = ui->le_laserInnerDia->text().toFloat();
        /*Erron*/
        if (initSize == 0)
        {
            ui->le_laserInnerDia->setText(QString::number(hex));
        }
        else
        {
            /*first*/
            if(DistenceShort != 0)
            {
                if(DistenceLong_max == 0)
                {
                    if(hex < DistenceShort)
                    {
                        DistenceLong_max = DistenceShort;
                        DistenceLong_min = DistenceShort;
                        distence = DistenceShort;
                    }
                    else
                    {
                        DistenceLong_max = hex;
                        DistenceLong_min = hex;
                        distence = hex;
                    }
                }
            }
            else
            {
                if(DistenceLong_max == 0)
                {
                    DistenceLong_max = hex;
                    DistenceLong_min = hex;
                    distence = hex;
                }
            }
            if(DistenceLong_max != 0)
            {
                if(hex > DistenceLong_max)
                {
                    DistenceCount ++;
                    if(DistenceCount > 2)
                    {
                        DistenceLong_max = hex;
                        DistenceCount = 0;
                    }
                }
                else if(hex < DistenceLong_min)
                {
                    DistenceCount ++;
                    if(DistenceCount > 3)
                    {
                        DistenceLong_min = hex;
                        DistenceCount = 0;
                    }
                }
                else
                {
                    if((hex < (DistenceLong_max * 0.8))&&(hex >= DistenceLong_min))
                    {
                        if((hex > (distence * 1.1))||(hex < (distence * 0.9)))
                        {
                            DistenceCount ++;
                            if(DistenceCount > 2)
                            {
                                distence = hex;
                                DistenceCount = 0;
                            }
                        }
                    }
                }
            }

        }
        ui->le_laserInnerDia->setText(QString::number(distence));
        /*
        else if(hex < initSize){
            ui->le_laserInnerDia->setText(QString::number(hex));
        }*/
        float result = ui->le_laserInnerDia->text().toFloat() - ui->le_laserOuterDia->text().toFloat();
        if(result < 0)
        {
            result = 0;
        }
        mStandardPara->distance=result;
        if(m_postDeviceDetail_flag)
        {
            putDetailFun("2");
        }
        ui->lineEdit_4->setText(QString::number(result));
        /*----zhanglong*/
        if(_orderBegin)
        {
            if(result < 20)
            {
                Alarm_Count ++;
                if(Alarm_Count > 4)
                {
                    Alarm_Count = 5;
                    m_systemStatus |= 0x1000;
                }
            }
            else
            {
                if(Alarm_Count != 0)
                {
                    Alarm_Count --;
                }
                else
                {
                    m_systemStatus &= 0xefff;
                }
            }
        }
    }

}
void PunchingMachine::readLDMCom(){
    if(m_ldmCom->canReadLine()){
        DistenceWorkCount1 = 0;
        QString temp = m_ldmCom->readAll();
        QString tempmid = temp.mid(2, 5);
        float hex = tempmid.toFloat();
        DistenceShort = hex * 1000.00;
        ui->le_laserOuterDia->setText(QString::number(hex * 1000.00));
    }
}

/*void PunchingMachine::readScaleCom()
{
    if(m_scaleCom->canReadLine()){
        QString temp = m_scaleCom->readAll();

        if(temp.contains("pcs") && temp.length()<15){
            QString count = temp.right(11).remove("pcs");
            ui->le_PScaleCount->setText(count);
        }

        if(temp.contains("ST")){
            if(temp.startsWith("\r\r")){
                temp = temp.remove(0,1);
            }
            QString scaleWeight;
            scaleWeight = temp.mid(6,8);
            ui->le_PScaleWeight->setText(scaleWeight);
        }
    }


}
*/

void PunchingMachine::readScaleCom()
{
    //2018.11.20 Chen Jiangang Reduce the frequency of Scale calculation for resource usage
    readScaleComDelay_count++;
    qDebug() << "\n\n ~~~~~ readScaleComDelay_count:" << readScaleComDelay_count;

    if ( readScaleComDelay_count >= 5)
    {
        if (m_scaleCom->canReadLine() ) {


            QString temp = m_scaleCom->readAll();
            qDebug() << "\n\n ~~~~~ temp scale readAll:" << temp;
            //20181019 fix bug of GOOD patrs at UI sometimes show "10 S" or "10 ST"
            if (temp.contains("pcs") &&temp.contains("g\n") &&(temp.indexOf("g\n")<temp.indexOf("pcs")))//T-Scale show pcs  "1234567pcs\n"
            {
                qDebug() << "\n\n pcs:" << temp;
                QString pcs="pcs";
                //if (temp.mid(7,4)=="pcs\n")
                int indexOfpcs=0;
                indexOfpcs=temp.indexOf(pcs); //return the index position of first occurence of "pcs\n"
                qDebug() << "\n\n return the index position of first occurence of pcs:" << indexOfpcs;
                if (indexOfpcs>=7) //make sure the pcs including 7 number:1234567pcs
                {
                    //QString count = temp.right(11).remove("pcs\n");
                    //~~~~~ temp scale readAll: "      7pcs\n"
                    QString count;

                    // 2018/10/30 Chenjiangang @SVRU Tianjing
                    //get rid of Empty string due to noise when scale is wired with RS232 cable longer than 10m
                    if(!temp.mid(indexOfpcs-7,7).isEmpty())
                    {
                        count =temp.mid(indexOfpcs-7,7);
                        qDebug() << "\n\n ~~~~~ count" << count;

                        ui->le_PScaleCount->setText(count.trimmed());
                        mStandardPara->calibrationCount = count.trimmed();
                        mStandardPara->scaleCount=count.trimmed();
                        if(m_postDeviceDetail_flag)
                        {
                            putDetailFun("1");
                            putDetailFun("4");
                        }
                    }
                }


            }

            //chenjiangang,20181019,T-Scale is used in G-IOT project installed with 26sets
            //Chenjiangang,20181122, add "ST,NT" at Tare condition besides of "ST,GS" at normal condition
            if (temp.contains("ST,")&&temp.contains("kg\r")&&(temp.indexOf("ST,")<temp.indexOf("kg\r")))
            {
                qDebug() << "\n\n string includig  ST,GS/ST,NT and kg\r:" << temp;
                QString ST="ST,";
                int indexOfST=0;
                indexOfST=temp.indexOf(ST); //return the index position of first occurence of "pcs\n"
                qDebug() << "\n\n return the index position of first occurence of  ST," << indexOfST;
                if (indexOfST>=0) //make sure the total weight including "ST,GS"
                {
                    // if (temp.startsWith("\r\r")) {
                    //if(temp.mid(0,7)=="\r\rST,GS"){
                    qDebug() << "\n\n ~~~~~ temp whole string before remove:" << temp;
                    //~~~~~ temp whole string before remove: "\r\rST,GS   0.038kg\r    6.45546 g\n"
                    //temp = temp.remove(0,1);
                    //~~~~~ temp whole string after remove: "\rST,GS   0.038kg\r    6.45546 g\n"  //2018.8.10.  2g accuracy Tscale
                    //              ~~~~~ temp scale readAll: "ST,GS   0.742kg\r          3 g\r\n" //2018.11.17  1g accuracy Tscale
                    //"\rST,GS    0.70kg\r    35.1217 g\n
                    QString scaleWeight;
                    // ~~~~~scaleWeight "   0.014"
                    // ~~~~~scaleWeight "0000.014"
                    // ~~~~~scaleWeight "  0.064k"
                    // ~~~~~scaleWeight "0pcs\n\r\rS"
                    // ~~~~~ temp scale readAll: "s\n\r\rST,GS   0.064kg\r"
                    // ~~~~~scaleWeight ",GS   0."
                    //"\r\rST,GS    0.466kg\r    46.1190 g\n"
                    //"\rST,GS   0.100kg\
                    //"\rST,GS12345678kg\
                    // 2018/10/30 Chenjiangang @SVRU Tianjing
                    //get rid of Empty string due to noise when scale is wired with RS232 cable longer than 10m
                    if(!temp.mid(indexOfST+5,8).isEmpty())
                    {
                        scaleWeight =temp.mid(indexOfST+5,8);
                        qDebug() << "\n\n ~~~~~scaleWeight" <<scaleWeight;
                        ui->le_PScaleWeight->setText(scaleWeight.trimmed());
                        mStandardPara->scaleWeight = scaleWeight;
                        if(m_postDeviceDetail_flag)
                        {
                            putDetailFun("3");
                        }
                        emit showScaleWeight(mStandardPara->scaleWeight);

                    }
                }




            }


            //chenjiangang,20181024, compare auto calibraiton count with Tscale counts and compensate cali-unitweight
            if (temp.contains("kg\r") &&temp.contains("g\n") &&(temp.indexOf("kg\r")<temp.indexOf("g\n"))) //get unitWeight before g\n
            {
                qDebug() << "\n\n string includig kg_r  g\n:" << temp;
                QString kg_r="kg\r";
                int indexOfkg_r=0;
                indexOfkg_r=temp.indexOf(kg_r); //return the index position of first occurence of "pcs\n"
                qDebug() << "\n\n return the index position of first occurence of  kg_r" << indexOfkg_r;
                if (indexOfkg_r>=0) //make sure the total weight including "kg_r"
                {

                    qDebug() << "\n\n ~~~~~ temp whole string before remove:" << temp;
                    //~~~~~ temp whole string after remove: "\rST,GS   0.038kg\r    5.789AB g\n"
                    //~~~~~ temp whole string after remove: "\rST,GS   0.038kg\r12345.789AB g\n"
                    //"\rST,GS    0.70kg\r    35.1217 g\n
                    QString scale_unitWeight;
                    //~~~~~ temp whole string after remove: "\rST,GS   0.038kg\r12345.789AB g\n"
                    //"\r\rST,GS    0.466kg\r    46.1190 g\n"

                    // 2018/10/30 Chenjiangang @SVRU Tianjing
                    //get rid of Empty string due to noise when scale is wired with RS232 cable longer than 10m
                    if(!temp.mid(indexOfkg_r+3,11).isEmpty())
                    {

                        scale_unitWeight =temp.mid(indexOfkg_r+3,11);
                        mStandardPara->scale_unitWeight = scale_unitWeight;
                        qDebug() << "\n\n ~~~~~mStandardPara->scale_unitWeight" << mStandardPara->scale_unitWeight;
                        emit showscale_unitWeight(mStandardPara->scale_unitWeight);
                    }
                }


            }
            //TODO 20180806 Need confirm this
            //20181016 Chenjiangang update parts counting auto calibraiton method
            float currentWeight = mStandardPara->scaleWeight.toFloat()*1000;
            // float currentWeight = scaleWeight.toFloat()*1000;
            float currentUnitWeight = mStandardPara->scale_unitWeight.toFloat();

            qDebug() << "~~~~~ currentWeight: " << currentWeight;
            qDebug() << "~~~~~ currentScaleUnitWeight: " << currentUnitWeight;
            qDebug() << "~~~~~ 222222222222222222222222222222222222222222222222222222222 ";

            m_scaleAmendInstance->getScaleSourceValue(currentWeight, currentUnitWeight);
            connect(this,SIGNAL(sendUw(float)),m_scaleAmendInstance,SLOT(getScaleUw(float)));
            connect(m_scaleAmendInstance,SIGNAL(sendCalibrationCount(int,float)),this,SLOT(getCalibrationCount(int,float)));


        }

        readScaleComDelay_count=0;
    }
#ifdef LINGHENG
    if(m_scaleCom->canReadLine()) {
        QString temp =  QString(m_scaleCom->readLine());
        mStandardPara->scaleWeight = QString::number( temp.mid(4,6).toFloat()/10);
        mStandardPara->scale_unitWeight = QString::number( temp.mid(16,6).toFloat()/10);
        mStandardPara->scaleCount = QString::number(temp.mid(22,6).toInt());
        emit showScaleWeight(mStandardPara->scaleWeight);
        emit showScaleCount(mStandardPara->scaleCount);
        if(m_postDeviceDetail_flag) {
            putDetailFun("16");
            putDetailFun("20");
        }

        //TODO 20180806 Need confirm this
        float currentWeight = mStandardPara->scaleWeight.toFloat();
        float currentUnitWeight = mStandardPara->scale_unitWeight.toFloat();
        m_scaleAmendInstance->getScaleSourceValue(currentWeight, currentUnitWeight);
        connect(this,SIGNAL(sendUw(float)),m_scaleAmendInstance,SLOT(getScaleUw(float)));
        connect(m_scaleAmendInstance,SIGNAL(sendCalibrationCount(int,float)),this,SLOT(getCalibrationCount(int,float)));
    }
#endif
}

void PunchingMachine::on_btn_SpotCheck_clicked()
{
    ui->btn_SpotCheck->setDisabled(true);
    m_systemStatus |= 0x4000;
    Equipment_ckeck = true;
    initSpotCheckEquipmentDialog();
}


void PunchingMachine::on_btn_QCCheck_clicked()
{

}

void PunchingMachine::firstProductionOK_toScanOperator2()
{
    m_systemStatus |= 0x4000;
    ui->btn_FirstCheck->setDisabled(true);
}

void PunchingMachine::firstQcCheck2()
{
    m_systemStatus |= 0x4000;
    ui->btn_QCCheck->setDisabled(true);
}

void PunchingMachine::initOrderRecordShow()
{
    ProductionVariant productinfo;
    queryCurrentOrder(productinfo,"");
    if (!productinfo.TaskId.isEmpty() && !productinfo.ProductName.isEmpty() && !productinfo.WorkNum.isEmpty() )
    {
        showProductionOrder();
    }
}

void PunchingMachine::httpRegister_slots(bool status)
{
    /*----zhanglong*/
    if(status)
    {
        m_systemStatus &= 0xdfff;
    }
    else
    {
        m_systemStatus |= 0x2000;
    }
    if(status && !m_register_flag)
    {
        m_register_flag = true;
        m_httpClient->registerDeviceInfo( m_deviceInfo->deviceType,m_deviceInfo->deviceId,"register",QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    }
}

void PunchingMachine::startFirstProduction_slots()
{
    //chenjiangang 20181018 To add parts counting auto calibration flag clear
    //ScaleAmendCalibration:: getScaleSourceValue
    // m_firstWeightFlag=0
    ScaleAmendCalibration::m_firstWeightFlag = false;
    m_orderFinish_flag = false;
    _orderBegin = true;
    m_systemStatus &= 0x7fff;
    startTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    sendUpdateTodayTask();  //订单开始只抛5号数据
    //send7Datas_first();
    _timerSendToserver->start(3000);
    ui->btn_FirstCheck->setEnabled(true);
    ui->btn_QCCheck->setEnabled(true);
}

void PunchingMachine::on_settingBtn_clicked()
{
    emit openSettingSignal();
}

void PunchingMachine::spotCheckManualExecute()
{
    //TODO
}


void PunchingMachine::getLaserDistance(QString laserDistance)
{
    ui->le_laserInnerDia->setText(laserDistance.append(" m"));
}

void PunchingMachine::recordScaleData_slots()
{
    if ( mStandardPara->scaleWeight.toFloat()*1000 <=0)
    {
        MyMessageDialog::message(this,"警告","请检查电子秤是否设置关闭零点跟踪！");
    }

    DataBaseQuery query(DataBase::getDataBase());
    DataBase::getDataBase().open();
    DataBase::getDataBase().transaction();
    QMap<QString,QVariant> map_Save;
    map_Save.insert(DBTab_PunchingMachine::_TAB_PUNCHINGMACHINE_SCALE_WEIGHT,QVariant(mStandardPara->scaleWeight.toFloat()));
    map_Save.insert(DBTab_PunchingMachine::_TAB_PUNCHINGMACHINE_SCALE_COUNT,QVariant( ui->le_PScaleCount->text().toInt()));
    map_Save.insert(DBTab_PunchingMachine::_TAB_PUNCHINGMACHINE_TASK_ID,QVariant(m_current_taskId));
    map_Save.insert(DBTab_PunchingMachine::_ADD_TIME,QVariant(QDateTime::currentDateTime()));

    query.insert(DBTab_PunchingMachine::TAB_PUNCHINGMACHINE,map_Save);

    DataBase::getDataBase().commit();
    DataBase::getDataBase().close();
    DataBase::getDataBase().open();
    DataBase::getDataBase().transaction();
    QString str;
    str = "SELECT "
          " SUM(" + DBTab_PunchingMachine::TAB_PUNCHINGMACHINE + "." + DBTab_PunchingMachine::_TAB_PUNCHINGMACHINE_SCALE_WEIGHT + "),"\
                                                                                                                                  " SUM(" + DBTab_PunchingMachine::TAB_PUNCHINGMACHINE + "." + DBTab_PunchingMachine::_TAB_PUNCHINGMACHINE_SCALE_COUNT + ")"\
                                                                                                                                                                                                                                                         " FROM "  + DBTab_PunchingMachine::TAB_PUNCHINGMACHINE +\
            " WHERE " + DBTab_PunchingMachine::TAB_PUNCHINGMACHINE + "." + DBTab_PunchingMachine::_TAB_PUNCHINGMACHINE_TASK_ID + " = " + "\""+ m_current_taskId + "\"";

    query.execQString(str);
    if (query.next()) {
        m_current_order_finished_weight = query.value(0).toFloat();
        m_current_order_finished_count = query.value(1).toInt();
        mStandardPara->totalCount_FromScale = QString::number(m_current_order_finished_count);
    }
    if(ui->btn_manual->property(UserRole).toBool() == false )
        ui->le_calibratedCount->setText(mStandardPara->calibrationCount);
    putDetailFun("22");//Put the scale total Count;
    DataBase::getDataBase().commit();
    DataBase::getDataBase().close();
    MyMessageDialog::message(0,"提示！","当前称重存储本地数据库成功！",1500);
}

void PunchingMachine::initAccelarateScale()
{
    m_accelarateScale = new AccelarateScale(m_usbPortName.port3_name,"9600",(DataBitsType)8,PAR_NONE,STOP_1);
    connect(m_accelarateScale,   SIGNAL(laserDistance(QString)),    this,   SLOT(getLaserDistance(QString)));
}

void PunchingMachine::getCalibrationCount(int calibrationCount,float unitweight)
{
    char fmt[]="%.2f";
    QString uw_str;
    uw_str.sprintf(fmt,unitweight);
    if(ui->btn_manual->property(UserRole).toBool() == false )
        ui->le_calibratedCount->setText(QString::number(calibrationCount));
    ui->le_uw->setText(uw_str);
    mStandardPara->scale_unitWeight = uw_str;
    if(m_postDeviceDetail_flag)
    {
        putDetailFun("5");
    }
}
void PunchingMachine::postWarnData(QString alarm, QString createtime)
{
    QJsonObject obj;
    obj.insert("alarm", alarm );
    obj.insert("createTime", createtime );
    m_httpClient->postWarningInfo( m_deviceInfo->deviceType,
                                   m_deviceInfo->deviceId,
                                   mParent->_productionVariant.TaskId,  obj );
}
/*----zhanglong*/
void PunchingMachine::Distance_mec_restart()
{
    QByteArray writedDataSec;
    writedDataSec.resize(1);
    writedDataSec[0] = 0x4F;
    if((DistenceWorkCount1 > 2)&&(DistenceWorkCount1 < 5))
    {
        emit toggleAutoSend(false);
        DistenceWorkCount1 ++;
        m_ldmCom->write(writedDataSec);
        emit toggleAutoSend(true);
    }
    if(DistenceWorkCount1 > 4)
    {
        emit toggleAutoSend(false);
        DistenceWorkCount1 = 0;
        initLaser_distance_measuring();
        m_ldmCom->write(writedDataSec);
        emit toggleAutoSend(true);
    }

    if((DistenceWorkCount2 > 2)&&(DistenceWorkCount2 < 5))
    {
        emit toggleAutoSend(false);
        DistenceWorkCount2 ++;
        m_ldmCom2->write(writedDataSec);
        emit toggleAutoSend(true);
    }
    if(DistenceWorkCount2 > 4)
    {
        emit toggleAutoSend(false);
        DistenceWorkCount2 = 0;
        initLaser_distance_measuringSec();
        m_ldmCom2->write(writedDataSec);
        emit toggleAutoSend(true);
    }
}

void PunchingMachine::LEDFrashCircleTimeSlot()
{
    /*status show*/
    /*Add Alarm text----zhanglong*/
    if(!_orderBegin)
    {
        m_systemStatus &= 0xefff;       /*clear Alarm*/
    }
    QStringList list;
    if(l_Equipment_ckeck != Equipment_ckeck)
    {
        if(Equipment_ckeck)
        {
            list << tr("请设备维护人员对设备进行点检！");
            ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);
        }
        else
        {
            list.clear();
        }
        l_Equipment_ckeck = Equipment_ckeck;
    }

    if (l_QC_Scan_ckeck != QC_Scan_ckeck)
    {
        if(QC_Scan_ckeck)
        {
            list << tr("请QC人员对设备进行巡检！");
            ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);
        }
        else
        {
            if (!l_Equipment_ckeck){
                list.clear();
            }
        }
        l_QC_Scan_ckeck = QC_Scan_ckeck;
    }
    if(l_systemStatus != m_systemStatus)
    {
        /*LED Fresh*/
        if(m_systemStatus & 0x000f)
        {
            qDebug() << "+++++++++++++++ZZZZZZZZ:" <<m_systemStatus;
            m_ammeterDate->writeCmd("06","0F","00","10","RTU","02","04 00",false);
        }
        else
        {
            if(m_systemStatus & 0xf000)
            {
                qDebug() << "-------------ZZZZZZZZ:" <<m_systemStatus;
                m_ammeterDate->writeCmd("06","0F","00","10","RTU","02","02 00",false);
            }
            else
            {
                m_ammeterDate->writeCmd("06","0F","00","10","RTU","02","09 00",false);
            }
        }
        l_systemStatus = m_systemStatus;

        if(Equipment_ckeck)
        {
            list << tr("请设备维护人员对设备进行点检！");
            /*ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);*/
        }
        else
        {
            list.clear();
        }
        if(QC_Scan_ckeck)
        {
            list << tr("请QC人员进行巡检！");
            /*ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);*/
        }
        else
        {
            if (!l_Equipment_ckeck){
                list.clear();
            }
        }

        if(m_systemStatus)
        {
            if(m_systemStatus & 0x0001)
            {
                list.append(AlarmList.at(0));
            }
            if(m_systemStatus & 0x0002)
            {
                list.append(AlarmList.at(1));
            }
            if(m_systemStatus & 0x0004)
            {
                list.append(AlarmList.at(2));
            }
            if(m_systemStatus & 0x1000)
            {
                list.append(AlarmList.at(12));
            }
            if(m_systemStatus & 0x2000)
            {
                list.append(AlarmList.at(13));
            }
            if(m_systemStatus & 0x4000)
            {
                list.append(AlarmList.at(14));
            }
            if(m_systemStatus & 0x8000)
            {
                list.append(AlarmList.at(15));
            }
            ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);
        }
        else
        {
            /*list.removeAll();*/
            if((!Equipment_ckeck) && (!QC_Scan_ckeck))
            {
                list.clear();
                ui->spotCheckScroll->hide();
            }
        }
        //list.append(AlarmList.at(2));
        //list = AlarmList.at(0)+AlarmList.at(2)+AlarmList.at(3)+AlarmList.at(4);
        if (!list.isEmpty()){
            for (int i=0;i<list.size();i++){
                QString str = list.at(i);
                if (str.trimmed()!=""){
                    postWarnData(str,QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
                }
            }
        }

    }
    //qDebug() << "~~~~~~ZZZZZZZZ~~~~~~~~~~~~~~~~~~~~:" <<l_systemStatus<<m_systemStatus;
}


void PunchingMachine::on_btn_manual_clicked()
{

    if( ui->btn_manual->property( UserRole).toBool() == true)
    {
        ui->le_calibratedCount->setFocus();
        QMouseEvent event(QEvent::MouseButtonPress, QPoint(),
                          Qt::NoButton, Qt::NoButton, Qt::NoModifier);
        QApplication::sendEvent(ui->le_calibratedCount, &event);
        return;
    }

    PerssionDlg dlg;
    if( 0 ==  dlg.exec() )
    {
        ui->btn_manual->setProperty(UserRole, true);
        ui->le_calibratedCount->setReadOnly(false);
        ui->le_calibratedCount->installEventFilter(this);
        ui->le_calibratedCount->setFocus();
        QMouseEvent event(QEvent::MouseButtonPress, QPoint(),
                          Qt::NoButton, Qt::NoButton, Qt::NoModifier);
        QApplication::sendEvent(ui->le_calibratedCount, &event);
    }
    else
    {
        ui->btn_manual->setProperty(UserRole, false);
    }
}

void PunchingMachine::on_btn_test_clicked()
{
    ui->le_calibratedCount->setText(  QString::number(ui->le_calibratedCount->text().toInt()+1 ));
}

void PunchingMachine::on_btn_contact_clicked()
{
    connectDlg dlg;
    dlg.exec();
}

void PunchingMachine::sendNotGood()
{
    m_httpClient->posNotGood(m_deviceInfo->deviceType,
                               m_deviceInfo->deviceId,
                               mParent->_productionVariant.TaskId,
                               "task",
                               ui->le_bad->text().toInt()
                               );
}
